<?php

namespace App\Jobs;

use App\Models\PushUser;
use App\Models\SystemConfig;
use App\Tools\FindUsers;
use App\Tools\Logs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ProcessDispatch implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $tasks;

    private $maxGetOrderNum;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($tasks)
    {
        $this->tasks = $tasks;
        // 获取最大接单人数
        $this->maxGetOrderNum = SystemConfig::findValue('dispatch.maxGetOrderNum2', 64);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $openDispatchNum = PushUser::where('status', 1)->count();

        $dispatchTask = new FindUsers($this->tasks, $openDispatchNum);
        if ($this->tasks['is_zqd'] == 2) {
            // 普通单
            Logs::info("普通销量单", [], 'dispatch', $this->tasks['task_code']);
            $dispatchTask->run();
        }elseif($this->tasks['is_zqd'] == 1){
            // 增权单
            Logs::info("增权单", [], 'dispatch', $this->tasks['task_code']);
            $dispatchTask->runZqd();
        }else{
            Log::info("无法识别单类型 {$this->tasks['task_code']}[{$this->tasks['is_zqd']}]");
            // 释放订单共享锁
            $dispatch_task_id = json_decode(Redis::get("dispatch_task_code"), true);
            $dispatch_taskid_key = array_search($this->tasks['id'], $dispatch_task_id);
            array_splice($dispatch_task_id, $dispatch_taskid_key, 1);
            Redis::set("dispatch_task_code", json_encode($dispatch_task_id));
        }
    }
}
